<script setup>
import { nextTick, onMounted, onUnmounted, ref } from 'vue'
import AMapLoader from '@amap/amap-jsapi-loader'
import { Search, Location, ArrowDown } from '@element-plus/icons-vue'
window._AMapSecurityConfig = {
  securityJsCode: '29833ca366ee2f832a6f1faa6ed8dc21'
}

const searchText = ref('')
const map = ref(null) //地图
const geocoder = ref(null) //地图编码
const scale = ref(null) // 比例尺
const toolBar = ref(null) // 缩放工具条
const geolocation = ref(null) //定位
let autoComplete = ref(null) //输入提示
const showPanel = ref(false) //搜索结果面板
/**
 * 起点、终点
 */
let startLngLat = null
let startMarker = null
let endLngLat = null
let endMarker = null
let drivingRoute = null

onMounted(() => {
  initMap()
})

async function initMap(e) {
  await AMapLoader.load({
    key: '0766d8928a71853c3c4649a1fd4a37ae',
    version: '2.0',
    plugins: [
      'AMap.Scale',
      'AMap.ToolBar',
      'AMap.Geocoder',
      'AMap.Geolocation',
      'AMap.HawkEye',
      'AMap.AutoComplete',
      'AMap.PlaceSearch',
      'AMap.InfoWindow',
      'AMap.ContextMenu',
      'AMap.Marker',
      'AMap.Driving'
    ]
  }).then((AMap) => {
    map.value = new AMap.Map('map_container', {
      viewMode: '3D', // 是否为3D地图模式
      zoom: '11', // 初始化地图级别
      doubleClickZoom: false,
      resizeEnable: true
    })
    /**
     * 地理编码器
     */
    geocoder.value = new AMap.Geocoder({
      radius: 1000,
      extensions: 'all'
    })
    /**
     * 比例尺
     */
    scale.value = new AMap.Scale({})
    map.value.addControl(scale.value)

    /**
     * 缩放工具条
     */
    toolBar.value = new AMap.ToolBar({
      offset: [20, 20]
    })
    map.value.addControl(toolBar.value)

    /**
     * 定位
     */
    geolocation.value = new AMap.Geolocation({
      showButton: false,
      showCircle: false,
      enableHighAccuracy: true,
      offset: [20, 90]
    })
    map.value.addControl(geolocation.value)
    locationUser()

    /**
     * 输入提示
     */
    poiSearch()

    // Event
    Event()

    //右键菜单
    rightClick()
  })
}
//定位
const locationUser = () => {
  geolocation.value.getCurrentPosition((status, result) => {
    if (status === 'complete') {
      console.log('定位成功', result)
      // 获取经纬度
      const { lng, lat } = result.position
      map.value.setCenter([lng, lat])
      map.value.setZoom(18)
    } else {
      console.log('定位失败', result)
    }
  })

  showPanel.value = false
}
//poi
const poiSearch = () => {
  let autoOption = {
    input: 'searchInput'
  }
  autoComplete.value = new AMap.AutoComplete(autoOption)
  let placeSearch = new AMap.PlaceSearch({
    map: map.value,
    city: '', // 减小搜索范围至某个城市
    pageSize: 5, // 单页显示结果条数
    pageIndex: 1, // 页码
    citylimit: false, // 是否强制限制在设置城市内搜索
    autoFitView: true,
    panel: 'panel' // 搜索结果列表将在此容器中进行展示。出不来时设置样式z-inde: 999
  })
  autoComplete.value.on('select', function (e) {
    //针对选中的poi实现自己的功能
    placeSearch.search(e.poi.name)
    showPanel.value = true
  })
}

// Event
const doubleClick = (e) => {
  console.log(`你在地图上点击了点，坐标为：${e.lnglat.lng},${e.lnglat.lat}`)
  const x = e.lnglat.lng
  const y = e.lnglat.lat
  infoShow(e, x, y)

  // 关闭panel
  showPanel.value = false
}
const click = (e) => {
  showPanel.value = false
}
const Event = () => {
  map.value.on('dblclick', doubleClick)
  // 添加点击地图任意位置的事件监听
  map.value.on('click', click)
}

// 信息窗体
const infoShow = (e, x, y) => {
  geocoder.value.getAddress(e.lnglat, (status, result) => {
    if (status === 'complete' && result.regeocode) {
      console.log(result)
      const address = result.regeocode.formattedAddress
      const infoContent = `
        <div style="padding:7px 0px 0px 0px;">
          <div class="global-header">当前位置</div>
          <p>经度: ${x}</p>
          <p>纬度: ${y}</p>
          <p>地址: ${address}</p>
        </div>
      `
      let infoWindow = new AMap.InfoWindow({
        content: infoContent
      })
      infoWindow.open(map.value, [x, y])
    }
  })
}

//右键菜单
const rightClick = (e) => {
  // 右键菜单
  const contextMenu = new AMap.ContextMenu()
  contextMenu.addItem('放大一级', function () {
    map.value.zoomIn()
  })
  contextMenu.addItem('缩小一级', function () {
    map.value.zoomOut()
  })
  //右键显示全国范围
  contextMenu.addItem(
    '缩放至全国范围',
    function (e) {
      map.value.setZoomAndCenter(4, [108.946609, 34.262324])
    },
    2
  )
  //设置起点
  contextMenu.addItem(
    '设置起点',
    function () {
      startLngLat = contextMenuPositon
      if (startMarker) {
        map.value.remove(startMarker)
      }
      startMarker = new AMap.Marker({
        map: map.value,
        position: startLngLat,
      })
      if (endLngLat) {
        console.log(startLngLat, endLngLat)
        driving([startLngLat.lng, startLngLat.lat], [endLngLat.lng, endLngLat.lat])
      }
    },
    4
  )
  // 设置终点
  contextMenu.addItem(
    '设置终点',
    function () {
      endLngLat = contextMenuPositon
      if (endMarker) {
        map.value.remove(endMarker)
      }
      endMarker = new AMap.Marker({
        map: map.value,
        position: endLngLat
      })
      if (startLngLat) {
        console.log(startLngLat, endLngLat)
        driving([startLngLat.lng, startLngLat.lat], [endLngLat.lng, endLngLat.lat])
      }
    },
    4
  )
  //地图绑定鼠标右击事件——弹出右键菜单
  let contextMenuPositon = null
  contextMenu.addItem(
    '添加标记',
    function () {
      let marker = new AMap.Marker({
        map: map.value,
        position: contextMenuPositon
      })
    },
    3
  )
  map.value.on('rightclick', function (e) {
    contextMenu.open(map.value, e.lnglat)
    contextMenuPositon = e.lnglat
  })
}
//路线规划
const driving = (startLngLat, endLngLat) => {
  if (drivingRoute) {
    drivingRoute.clear()
  }
   drivingRoute = new AMap.Driving({
    map: map.value,
    policy: 0,
    panel: 'driving',
    showTraffic: false, // 不显示实时路况
    hideMarkers: false, // 显示起始点和终点标记
    isOutline: true, // 显示路线轮廓
    autoFitView: true // 自动调整地图视野以完整显示路线
  })
  drivingRoute.search(startLngLat, endLngLat, function (status, result) {
    if (status === 'complete') {
      console.log(result.routes[0].steps)
      map.value.setCenter(startLngLat)
    }
  })
}
onUnmounted(() => {
  map.value?.destroy()
})
</script>

<template>
  <div class="map-wrapper">
    <div class="search-container">
      <div class="search-box">
        <el-input
          v-model="searchText"
          id="searchInput"
          placeholder="请输入地址"
          class="search-input"
          clearable
        >
          <template #prefix>
            <el-icon
              class="location-icon"
              @click="locationUser"
              ><Location
            /></el-icon>
          </template>
          <template #suffix>
            <el-icon
              class="search-icon"
              @click="locationUser()"
              ><Search
            /></el-icon>
          </template>
        </el-input>

        <div class="divider"></div>

        <div class="region-selector">
          <span class="region-text">四川</span>
          <el-icon class="arrow-icon"><ArrowDown /></el-icon>
        </div>
      </div>
    </div>
    <div
      id="panel"
      class="search-panel"
      v-show="showPanel"
    ></div>
    <div
      id="driving"
      class="drivinf-panel"
    ></div>
    <div id="map_container"></div>
  </div>
</template>

<style lang="scss" scoped>
.map-wrapper {
  position: relative;
  width: 100%;
  height: 100vh;
}

#map_container {
  padding: 0;
  margin: 0;
  width: 100%;
  height: 100%;
}

.search-container {
  position: absolute;
  top: 20px;
  left: 20px; /* 改变位置到左侧 */
  z-index: 1000;
  transform: none; /* 移除居中转换 */
}

.search-box {
  display: flex;
  align-items: center;
  background: #fff;
  border-radius: 25px;
  /* 移除阴影效果 */
  padding: 5px;
  /* 增大尺寸 */
  transform: scale(1.2); /* 放大1.2倍 */
  transform-origin: left top; /* 以左上角为缩放原点 */

  /* 移除悬停效果 */
}

.search-input {
  width: 350px; /* 增大宽度 */

  :deep(.el-input__wrapper) {
    box-shadow: none;
    background: transparent;
    border: none;
    padding: 0 15px;
  }

  :deep(.el-input__inner) {
    height: 45px; /* 增大高度 */
    line-height: 45px;
    border: none;
    font-size: 16px; /* 增大字体 */

    &::placeholder {
      color: #999;
    }
  }

  :deep(.el-input__prefix) {
    color: #666;
    cursor: pointer;
  }

  :deep(.el-input__suffix) {
    .search-icon {
      color: #999;
      cursor: pointer;
      /* 移除悬停效果 */
    }
  }

  :deep(.el-input__clear) {
    margin-right: 5px;
  }
}

.location-icon {
  cursor: pointer;
}

.divider {
  width: 1px;
  height: 24px;
  background: #e4e7ed;
  margin: 0 5px;
}

.region-selector {
  display: flex;
  align-items: center;
  padding: 0 20px;
  height: 45px; /* 增大高度 */
  cursor: pointer;
  /* 移除悬停效果 */
}

.region-text {
  font-size: 16px; /* 增大字体 */
  color: #333;
  margin-right: 5px;
}

.arrow-icon {
  font-size: 14px; /* 增大字体 */
  color: #999;
}
.arrow-icon {
  font-size: 14px; /* 增大字体 */
  color: #999;
}

.search-panel,
.drivinf-panel {
  position: absolute;
  top: 0px;
  right: 0px;
  z-index: 999;
}

// 简化搜索结果列表样式
.amap-poi-list {
  padding: 0;
  margin: 0;
}

.amap-poi-list-item {
  list-style: none;
  padding: 10px 15px;
  border-bottom: 1px solid #eee;

  &:last-child {
    border-bottom: none;
  }
}

.amap-poi-name {
  font-weight: bold;
  margin-bottom: 5px;
}

.amap-poi-address {
  font-size: 12px;
  color: #666;
}
</style>
